package cn.faifai.desktop.utils;

import cn.faifai.desktop.events.StageCloseEvent;
import cn.faifai.framework.utils.SingleEvenBus;
import com.google.common.eventbus.EventBus;
import javafx.stage.Stage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StageManager {
    private final Map<String, Stage> stages = new ConcurrentHashMap<>();
    private static final EventBus eventBus = SingleEvenBus.getInstance();
    private StageManager(){};
    private static class SingletonHolder{
        private static final StageManager INSTANCE = new StageManager();
    }
    public static StageManager getInstance(){
        return SingletonHolder.INSTANCE;
    }

    public void registerStage(String key, Stage stage){
        // 添加关闭请求时监听
        stage.setOnCloseRequest(event -> {
            eventBus.post(new StageCloseEvent(key, event));
        });
        stages.put(key, stage);
    }

    public void addCloseListener(Object listener) {
        eventBus.register(listener);
    }

    public Stage getStage(String key){
        return stages.get(key);
    }

    public void closeStage(String key){
        Stage stage = stages.get(key);
        if (stage != null){
            stage.close();
        }
        stages.remove(key);
    }

    public void closeAllStage(){
        for (Stage stage : stages.values()) {
            stage.close();
        }
        stages.clear();
    }

    public void showStage(String key){
        Stage stage = stages.get(key);
        if (stage != null){
            stage.show();
        }
    }

}
